﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TLSharp;

public partial class Game : System.Web.UI.Page
{
    public string CookieUserName = "";
    public string CookiePassword = "";
    public string AppGuid = System.Configuration.ConfigurationSettings.AppSettings["AppGuid"];

    protected void Page_Load(object sender, EventArgs e)
    {
        int GameID = System.Convert.ToInt32(Request["GameID"]);
        CookieUserName = Request.Cookies["TLUsername"] != null ? Request.Cookies["TLUsername"].Value : "";
        CookiePassword = Request.Cookies["TLPassword"] != null ? Request.Cookies["TLPassword"].Value : "";

        GetTurnStateResponse TurnReq = TouchLeagueService.GetTurnState(CookieUserName, CookiePassword, AppGuid, GameID);

        int OwnedTeamID = TurnReq.OwnedTeamID;
        int CurrentTurnTeamID = TurnReq.NextTurnTeamID;

        //You will now load the existing state of your game
        //MyGame Match = new MyGame(TurnReq.GameState);

        System.Text.StringBuilder ResponseText = new System.Text.StringBuilder();

        bool bStartPage = ((Request["bStartPage"] != null && Request["bStartPage"].Length != 0) ? true : false);

        if (bStartPage)
        {
            ResponseText.Append(@"<html xmlns='http://www.w3.org/1999/xhtml'>
                                    <head id='Head1' runat='server'>
                                         <title>Your Game Name</title>
                                        <meta name='viewport' content='width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;'/>
                                        <style type='text/css' media='screen'>@import 'm/iui.css';</style>
                                    <script type='application/x-javascript' src='m/iui.js'></script>
                                    </head>
                                    <body>
                                        <div class='toolbar'>
                                        <h1 id='pageTitle'>Your Game Name</h1>
                                        <a id='backButton' class='button' href='#'></a>
                                        <a class='button' target='_self' href='default.aspx'>Home</a>
                                    </div>");

        }
        ResponseText.Append("<ul id='Game" + TurnReq.GameID.ToString() + "-" + TurnReq.TurnID.ToString() + "' title='Game' selected='true'>");
        //build adcode
        if (TurnReq.HasAd)
        {
            ResponseText.Append(BuildAdCode(TurnReq));
        }
        if (OwnedTeamID == CurrentTurnTeamID)
        {
            //In this block you build the screen that users see when it is their turn
            //Check to see if the player is trying to make a move

            if (Request["MoveType"] != null)
            {
               
                //process the move
                //make sure the turns match so we don't double submit
                //This block is hit when the user selects an action.  For example, if the user click 'attack' you would procss that here:
                if (Request["TurnID"].ToString() == TurnReq.TurnID.ToString())
                {
                    //check availible moves 
                   
                    switch (Request["MoveType"].ToString())
                    {
                        case "Attack":
                            {
                                //Match.Attack(); 
                                break;
                            }
                        case "Defend":
                            {
                                //Match.Defend(); 
                                break;
                            }
                        case "Flee":
                            {
                                //Match.Flee(); 
                                break;
                            }                        
                    }

                    //set the turn state
                    bool bFinalize = false;
                    int NextTeamTurnID = 0;  //Retrieve the next player from you class: Match.NextPlayerID;
                    
                    //You will finalize the match when the game is over.  This code check for the condition 
                    //if(Match.MatchOver)
                    //{
                    //    bFinalize=true;
                    //   NextTeamTurnID=-100;
                    //}

                    string ScoreArray = ""; //Set the score array: Match.Challengee.Value<int>("TeamID").ToString() + "," + Match.GetScore(Match.Challengee).ToString() + "|" + Match.Challenger.Value<int>("TeamID").ToString() + "," + Match.GetScore(Match.Challenger).ToString();
                    string MatchString = "";//Server.UrlEncode(Match.ToJSON());
                    TouchLeagueService.SetTurnState(CookieUserName,CookiePassword,AppGuid,GameID,NextTeamTurnID,MatchString,ScoreArray,bFinalize);

                    //redirect back to the game.
                    Response.Redirect("Game.aspx?GameID=" + GameID.ToString());
                }
            }
            
            //this code builds the view of the page and presents the actions to the user:
            //todo: format board
            //ResponseText.Append("<li>" + GameStateText + "</li>");

            //You want to pass the the following variables to the Game.aspx page when executing an action.
            //ResponseText.Append(@"<li><a href='Game.aspx?MoveType=Attack&TurnID=" + TurnReq.TurnID.ToString()  + "&PlayerID=" + OwnedTeamID.ToString() + "&GameID=" + GameID.ToString() + "'>Attack:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></li>");
            //ResponseText.Append(@"<li><a href='Game.aspx?MoveType=Defend&TurnID=" + TurnReq.TurnID.ToString()  + "&PlayerID=" + OwnedTeamID.ToString() + "&GameID=" + GameID.ToString() + "'>Defend:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></li>");
            //ResponseText.Append(@"<li><a href='Game.aspx?MoveType=Flee&TurnID=" + TurnReq.TurnID.ToString()  + "&PlayerID=" + OwnedTeamID.ToString() + "&GameID=" + GameID.ToString() + "'>Flee:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></li>");
            


            //This builds the users view of the existing comments in short view.
            ResponseText.Append(BuildQuickComments(TurnReq));
          

            //this is a good place to output the list of actions taken by the other players since this player last played
            //foreach (string ThisAction in Match.ActionList.Take(10))
            //{
            //    ResponseText.Append("<li><div style='font-size:small;'>" + ThisAction.ToString() + "</div></li>");
            //}

            //ResponseText.Append("<li><a href='#OtherActions' target=_replace><div style='font-size:small;'>All...</div></a></li>");

            //This builds the  private notes interface that the player has taken on the game.
            ResponseText.Append(BuildQuickNotes(TurnReq));
            ResponseText.Append("</ul>");


            //This outputs ALL the actions so that the user can view the entire history.  This is good for short games but could slow the page down if you have a lot of actions to report.
            //int ActionProcessed = 0;
            //foreach (string ThisAction in Match.ActionList)
            //{
            //    if (ActionProcessed == 0) { ResponseText.Append("<ul id='OtherActions'>"); }
            //    ResponseText.Append("<li><div style='font-size:small;'>" + ThisAction.ToString() + "</div></li>");
               
            //    ActionProcessed++;
            //}



            //if (ActionProcessed > 0) { ResponseText.Append("</ul>"); }

            //These build the full list of comments and notes
            //ResponseText.Append(BuildFlatComments(TurnReq));
            //ResponseText.Append(BuildNotes(TurnReq));


            //here is where you would build forms to enhance the actions taken
            //ResponseText.Append(BuildAttackForm()); 

            
            Response.Write(ResponseText.ToString());
            Response.End();
        }
        else
        {
            //it is not this person's turn
           

            //ResponseText.Append("<li>" + GameStateText + "</li>");
            //it is this person's turn
           
            //This code loads in the list of other games for the user to determin if they have active turns in other games.
            BrowseMyGameResponse MyGames = TouchLeagueService.BrowseGames(CookieUserName, CookiePassword, AppGuid);

            if (MyGames.ActiveGames != null && MyGames.ActiveGames.Count > 0)
            {
                ResponseText.Append("<li><a href='#OtherActives'><div>Other Active Turns...<div style='background-color:Red;color:White;float:right;Padding:2px 2px 2px 2px;'>" + MyGames.ActiveGames.Count.ToString() + "</div></div></a></li>");
            }
            else
            {
                ResponseText.Append("<li>It is not your turn in any other games</li>");
                ResponseText.Append("<li><a href='#FindAMatch'><div>Find a New Match...</div></a></li>");

            }

            //show the last few comments(See above)
            ResponseText.Append(BuildQuickComments(TurnReq));
            


            //Show the actions(See Above)
            //foreach (string ThisAction in Match.ActionList.Take(10))
            //{
            //    ResponseText.Append("<li><div style='font-size:small;'>" + ThisAction.ToString() + "</div></li>");
            //}

            ResponseText.Append("<li><a href='#OtherActions'><div style='font-size:small;'>All...</div></a></li>");

            //Build Notes: See above
            ResponseText.Append(BuildQuickNotes(TurnReq));

            ResponseText.Append("</ul>");



            //All actions
            int ActionProcessed = 0;
            //foreach (string ThisAction in Match.ActionList)
            //{
            //    if (ActionProcessed == 0) { ResponseText.Append("<ul id='OtherActions" + TurnReq.GameID.ToString() + "-" + TurnReq.TurnID.ToString() + "' title='OtherActions'>"); }
            //    ResponseText.Append("<li><div style='font-size:small;'>" + ThisAction.ToString() + "</div></li>");
            //    ActionProcessed++;
            //}
            //if (ActionProcessed > 0) { ResponseText.Append("</ul>"); } 

            //All active turns
            if (MyGames.ActiveGames != null && MyGames.ActiveGames.Count > 0)
            {
                ResponseText.Append("<ul id='OtherActives' title='Active Turns'>");
                foreach (TLSharp.Game ThisGame in MyGames.ActiveGamesObjects)
                {
                    ResponseText.Append("<li><a href='Game.aspx?GameID=" + ThisGame.GameID.ToString() + "'> <table><tr><td>#" + ThisGame.Challengee.CurrentRank.ToString() + " " + ThisGame.Challengee.QuickName + "</td><td>" + ThisGame.Challengee.CurrentScore + "</td></tr><tr><td>#" + ThisGame.Challenger.CurrentRank.ToString() + " " + ThisGame.Challenger.QuickName + "</td><td>" + ThisGame.Challenger.CurrentScore + "</td></tr></table></a></li>");
                }
                ResponseText.Append("</ul>");
            }

            //All comments
            ResponseText.Append(BuildFlatComments(TurnReq));
            //All Private Notes
            ResponseText.Append(BuildNotes(TurnReq));

            Response.Write(ResponseText.ToString());
            
            Response.End();
        }

    }

    public string BuildAdCode(GetTurnStateResponse Req)
    {

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //string AdCode = "<a href='" + Req.AdURL + "' target=_blank style=''>" + Req.AdTitle + "</a>";
        string AdCode = "";
        AdCode = "<a href='" + Req.AdURL + "' target=_blank style=''>" + Req.AdTitle + "</a>";
        AdCode += "<br/><a href='" + Req.AdURL + "' target=_blank style='font-size:smaller;text-decoration:none;'>" + Req.AdText + "</a>";
        AdCode += "<br/><a href='" + Req.AdURL + "' target=_blank style='font-size:x-small;text-decoration:none;color:green;width:100%;'>" + Req.AdWebTag + "</a>";
        AdCode += "<br/>" + Req.AdFooter;


            sb.Append("<li><div id='AdDiv' name='AdDiv' style=''>" + AdCode + "</div></li>");
        return sb.ToString();
    }

    public string BuildQuickComments(GetTurnStateResponse TurnReq)
    {
        System.Text.StringBuilder ResponseText = new System.Text.StringBuilder();
        ResponseText.Append(@"<li style='background-color:#B3CDE8;'><a href='MakeNote.aspx?GameID=" + TurnReq.GameID.ToString() + "&OwnedTeamID=" + TurnReq.OwnedTeamID.ToString() + "'>Comments:<img src='images/green/plus.png' width=30px height=30px style='float:right'/></a></li>");

        if (TurnReq.FlatComments.Count > 0)
        {
            foreach (TeamNote ThisNote in TurnReq.FlatComments.Take(3))
            {
                GameTeam CommentingTeam = TurnReq.GameTeamObjects.Where(p => p.TeamID == ThisNote.TeamID).FirstOrDefault();
                ResponseText.Append("<li style='background-color:#B3CDE8;'><a href='MakeNote.aspx?GameID=" + TurnReq.GameID.ToString() + "&" + "ReplyToNoteID=" + ThisNote.NoteID.ToString() + "'><div style='font-size:smaller'>" + (TurnReq.OwnedTeamID == ThisNote.TeamID ? "<img src='images/blue/chat.png' width=25px height=25px/>" : "") + CommentingTeam.QuickName + ":" + (TurnReq.OwnedTeamID != ThisNote.TeamID ? "<img src='images/red/chat.png' width=25px height=25px/>" : "") + "<img src='images/smoke/undo.png' width=30px height=30px style='float:right'/><br/>" + ThisNote.Note + "</div>" + "</a></li>");
            }
            if (TurnReq.FlatComments.Count > 3)
            {
                ResponseText.Append(@"<li style='background-color:#B3CDE8;'><a href='#Notes'>All Comments...</a></li>");
            }
        }
        return ResponseText.ToString();

    }

    public string BuildFlatComments(GetTurnStateResponse TurnReq)
    {
        System.Text.StringBuilder ResponseText = new System.Text.StringBuilder();

        if (TurnReq.FlatComments.Count > 3)
        {
            int CommentProcessed = 0;
            ResponseText.Append(@"<li><a href='MakeNote.aspx?GameID=" + TurnReq.GameID.ToString() + "&OwnedTeamID=" + TurnReq.OwnedTeamID.ToString() + "'>Comments:<img src='images/green/plus.png' width=30px height=30px style='float:right'/></a></li>");
            foreach (TeamNote ThisNote in TurnReq.FlatComments)
            {
                if (CommentProcessed == 0) { ResponseText.Append("<ul id='Notes' title='Game Comments'>"); }

                GameTeam CommentingTeam = TurnReq.GameTeamObjects.Where(p => p.TeamID == ThisNote.TeamID).FirstOrDefault();
                ResponseText.Append("<li><a href='MakeNote.aspx?GameID=" + TurnReq.GameID.ToString() + "&" + "ReplyToNoteID=" + ThisNote.NoteID.ToString() + "&OwnedTeamID=" + TurnReq.OwnedTeamID.ToString() + "'><div style='font-size:smaller'>" + (TurnReq.OwnedTeamID == ThisNote.TeamID ? "<img src='images/blue/chat.png' width=25px height=25px/>" : "") + CommentingTeam.QuickName + ":" + (TurnReq.OwnedTeamID != ThisNote.TeamID ? "<img src='images/red/chat.png' width=25px height=25px/>" : "") + "<img src='images/smoke/undo.png' width=30px height=30px style='float:right'/><br/>" + ThisNote.Note + "</div>" + "</a></li>");
                CommentProcessed++;
            }
            if (CommentProcessed > 0) { ResponseText.Append("</ul>"); }
        }
        return ResponseText.ToString();
    }

    public string BuildQuickNotes(GetTurnStateResponse TurnReq)
    {
        System.Text.StringBuilder ResponseText = new System.Text.StringBuilder();
        ResponseText.Append(@"<li style='background-color:#B3CDE8;'><a href='MakeNote.aspx?GameID=" + TurnReq.GameID.ToString() + "&bPrivate=on" + "&OwnedTeamID=" + TurnReq.OwnedTeamID.ToString() + "'>Notes:<img src='images/green/plus.png' width=30px height=30px style='float:right'/></a></li>");

        if (TurnReq.PrivateNotes.Count > 0)
        {
            foreach (TeamNote ThisNote in TurnReq.PrivateNotes.Take(3))
            {
                GameTeam CommentingTeam = TurnReq.GameTeamObjects.Where(p => p.TeamID == ThisNote.TeamID).FirstOrDefault();
                ResponseText.Append("<li style='background-color:#B3CDE8;'><div style='font-size:smaller'>" + (TurnReq.OwnedTeamID == ThisNote.TeamID ? "<img src='images/blue/doc.png' width=25px height=25px/>" : "") + CommentingTeam.QuickName + ":" + (TurnReq.OwnedTeamID != ThisNote.TeamID ? "<img src='images/red/doc.png' width=25px height=25px/>" : "") + "<br/>" + ThisNote.Note + "</div>" + "</li>");
            }
            if (TurnReq.PrivateNotes.Count > 3)
            {
                ResponseText.Append(@"<li style='background-color:#B3CDE8;'><a href='#Notes'>All Notes...</a></li>");
            }
        }
        return ResponseText.ToString();

    }

    public string BuildNotes(GetTurnStateResponse TurnReq)
    {
        System.Text.StringBuilder ResponseText = new System.Text.StringBuilder();

        if (TurnReq.PrivateNotes.Count > 3)
        {
            int CommentProcessed = 0;
            ResponseText.Append(@"<li><a href='MakeNote.aspx?GameID=" + TurnReq.GameID.ToString() + "&bPrivate=on&OwnedTeamID=" + TurnReq.OwnedTeamID.ToString() + "'>Notes:<img src='images/green/plus.png' width=30px height=30px style='float:right'/></a></li>");
            foreach (TeamNote ThisNote in TurnReq.FlatComments)
            {
                if (CommentProcessed == 0) { ResponseText.Append("<ul id='Flat' title='Game Comments'>"); }

                GameTeam CommentingTeam = TurnReq.GameTeamObjects.Where(p => p.TeamID == ThisNote.TeamID).FirstOrDefault();
                ResponseText.Append("<li><div style='font-size:smaller'>" + (TurnReq.OwnedTeamID == ThisNote.TeamID ? "<img src='images/blue/doc.png' width=25px height=25px/>" : "") + CommentingTeam.QuickName + ":" + (TurnReq.OwnedTeamID != ThisNote.TeamID ? "<img src='images/red/doc.png' width=25px height=25px/>" : "") + "<br/>" + ThisNote.Note + "</div>" + "</li>");
                CommentProcessed++;
            }
            if (CommentProcessed > 0) { ResponseText.Append("</ul>"); }
        }
        return ResponseText.ToString();
    }
} 
